#!/usr/bin/env bash


_W_DEVICE=${_W_DEVICE:-en0}

help(){
    cat<<__EOF__
Usage: m wifi [OPTIONS] [ARGUMENTS]

Description: Manage your wifi connections on macOS

Options:
  --help                      Show this help message
  --status                    Show current wifi status
  --scan                      Scan for available wifi networks
  --showpassword [ESSID]      Show the password for a wifi network
  --list                      List known wifi networks
  --forget ESSID              Forget a wifi network
  --history                   Show wifi connection history
  --disable                   Turn off wifi
  --enable                    Turn on wifi
  --connect ESSID [PASSWORD]  Connect to a wifi network (prompt for password if not provided)
__EOF__
}

warning_msg(){
    echo "m-cli:"
    echo "  Airport command is deprecated in macOS 10.15 Catalina and later."
    echo "  This might not work as expected."
    echo "  Output below this line is generated by the 'airport' command."
    echo "-------------------------------------------------------------- "
}

wifi_status(){
    # XXX: Deprecated
    warning_msg
    /System/Library/PrivateFrameworks/Apple80211.framework/Versions/Current/Resources/airport -I
}


wifi_scan(){
    # XXX: Deprecated
    warning_msg
    /System/Library/PrivateFrameworks/Apple80211.framework/Versions/Current/Resources/airport -s
}

wifi_history(){
    #XXX: Deprecated
    warning_msg
    defaults read /Library/Preferences/SystemConfiguration/com.apple.airport.preferences | grep LastConnected -A 7
}

wifi_showpassword(){
    local ssid="${1}"
    security find-generic-password -D "AirPort network password" -a "$ssid" -gw
}

wifi_disable(){
    networksetup -setairportpower ${_W_DEVICE} off
}

wifi_enable(){
    networksetup -setairportpower ${_W_DEVICE} on
}

connect_network(){
    [ "$#" -lt 1  ] && help && exit 1

    local essid="$1"
    if [ "$#" -eq 1  ]; then
        read -s -r -p "Password: " password
    elif [ "$#" -eq 2 ]; then
        password="$2"
    fi
    networksetup -setairportnetwork "${_W_DEVICE}" "${essid}" "${password}"
}

wifi_list_known(){
    networksetup -listpreferredwirelessnetworks ${_W_DEVICE} | grep -v ^Preferred
}

wifi_forget(){
    if [ -z "$1" ]; then
        help && exit 1
    fi
    local essid="$1"
    sudo networksetup -removepreferredwirelessnetwork ${_W_DEVICE} "${essid}"
}

case $1 in
    --help)
        help
        ;;
    --scan)
        wifi_scan
        ;;
    --status)
        wifi_status
        ;;
    --disable)
        wifi_disable
        ;;
    --enable)
        wifi_enable
        ;;
    --list)
        wifi_list_known
        ;;
    --connect)
        shift
        connect_network "$@"
        ;;
    --history)
        shift
        wifi_history
        ;;
    --showpassword)
        shift
        wifi_showpassword "$@"
        ;;
    --forget)
        shift
        wifi_forget "$@"
        ;;
    *)
        help
        ;;
esac
